package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbMaterialMapper;
import com.tju.resource.mapper.TbSharperMapper;
import com.tju.resource.model.TbMaterial;
import com.tju.resource.model.TbSharper;
import com.tju.resource.server.TbSharperService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class TbSharperServiceImpl extends ServiceImpl<TbSharperMapper, TbSharper>
        implements TbSharperService {
    @Autowired
    private TbSharperMapper mapper;
    @Autowired
    private ChineseExceptionUtils zh_CH;
    @Autowired
    private TbMaterialMapper tbMaterialMapper;

    @Override
    public Result<Object> selectTbSharper(ClientParameters pa) {
        try {
            Integer pageNum = pa.getPage();//页码
            Integer pageSize = pa.getLimit(); //页数
            if (EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)) {
                pageNum = pageNum == 0 ? 1 : pageNum; //默认值
                pageSize = pageSize == 0 ? 10 : pageSize;//默认值
                Page<TbSharper> page = new Page<>(pageNum, pageSize);//分页
                QueryWrapper<TbSharper> qw = new QueryWrapper<>();
                qw.like("sharper_name", pa.getOne()); //查询模具具名称
                qw.like("sharper_serial_number", pa.getTwo());//查询磨具编号
                qw.orderByDesc("id");
                IPage<TbSharper> iPage = mapper.selectPage(page, qw);
                return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    @Override
    @Transactional
    public Result<Object> insertTbSharper(TbSharper tbSharper) {
        //String sharperName = tbSharper.getSharperName();//磨具名称
        String sharperSerialNumber = tbSharper.getSharperSerialNumber();//磨具编号
        if (EmptyUtils.isNotEmpty(checkSharperNameUnique(null, sharperSerialNumber)))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不能重复模具编号！");
        if (tbSharper.getResidualLife() > tbSharper.getInitialLife()) {
            throw new ServiceException("初始寿命必须要大于剩余寿命！");
        }
        if (mapper.insert(tbSharper) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.AddedSuccessfully);
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.AddFailed);
    }

    @Override
    @Transactional
    public Result<Object> updateTbSharper(TbSharper tbSharper) {
        try {
            TbSharper tb = mapper.selectById(tbSharper.getId()); //查询磨具
            if (EmptyUtils.isEmpty(tb)) {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不存在该模具！");
            }
            //String sharperName = tbSharper.getSharperName();//磨具名称
            String sharperSerialNumber = tbSharper.getSharperSerialNumber();//磨具编号
//            if (!tb.getSharperName().equals(sharperName)) {
//                if (EmptyUtils.isNotEmpty(checkSharperNameUnique(sharperName, null))) {
//                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "模具名称重复！");
//                }
//            }
            if (!tb.getSharperSerialNumber().equals(sharperSerialNumber)) {
                if (EmptyUtils.isNotEmpty(checkSharperNameUnique(null, sharperSerialNumber))) {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "模具编号重复！");
                }
            }
            tbSharper.setUpdateTime(new Date());
            if (mapper.updateById(tbSharper) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyModified);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailToEdit);
    }

    @Override
    @Transactional
    public Result<Object> deleteTbSharper(TbSharper tbSharper) {
        try {
            if (EmptyUtils.isNotEmpty(tbSharper.getId())) {
                QueryWrapper<TbMaterial> qw = new QueryWrapper<>();
                qw.eq("sid", tbSharper.getId());
                if (EmptyUtils.isNotEmpty(tbMaterialMapper.selectList(qw))) {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "该模具被使用了不能删除！");
                }
                //不存在就删除
                if (mapper.deleteById(tbSharper.getId()) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyDeleted);
                }
            } else {
                ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailedToDelete);
    }

    /**
     * 判断唯一的磨具名称和编号
     *
     * @param
     * @return
     */
    public TbSharper checkSharperNameUnique(String sharperName, String sharperSerialNumber) {
        QueryWrapper<TbSharper> qw = new QueryWrapper<>();
        if (EmptyUtils.isNotEmpty(sharperName)) {
            qw.eq("sharper_name", sharperName).or();
        }
        if (EmptyUtils.isNotEmpty(sharperSerialNumber)) {
            qw.eq("sharper_serial_number", sharperSerialNumber);
        }
        List<TbSharper> tbSharpers = mapper.selectList(qw);
        for (TbSharper tbSharper : tbSharpers) {
            if (EmptyUtils.isNotEmpty(tbSharper)) {
                return tbSharper;
            }
        }
        return null;
    }
}
